package com.tql.pandian.service.impl;

import com.ruoyi.common.core.utils.CalculatedValueUtil;
import com.tql.pandian.entity.analysis.TqlCaseAnlasysEntity;
import com.tql.pandian.entity.analysis.TqlStapoutChangeEntity;
import com.tql.pandian.entity.analysis.dto.LastCaseDTO;
import com.tql.pandian.entity.analysis.vo.LastCaseVo;
import com.tql.pandian.entity.vo.CaseAnalsysDto;
import com.tql.pandian.mapper.StockCalculateMapper;
import com.tql.pandian.service.IAnotherDataBaseService;
import com.tql.pandian.service.IGenCostAnalysService;
import com.tql.pandian.service.IStapOutChangeService;
import com.tql.pandian.service.IStockCalculateService;
import com.tql.pandian.util.CommonUtilHll;
import com.ruoyi.common.core.constant.CommonUtil;
import com.tql.pandian.vo.TqlStapProlossItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StockCalculateService implements IStockCalculateService {


    @Autowired
    private StockCalculateMapper stockCalculateMapper;

    @Autowired
    private IStapOutChangeService stapOutChangeService;

    @Autowired
    private IAnotherDataBaseService anotherDataBaseService;

    @Autowired
    private IGenCostAnalysService genCostAnalysService;

    @Override
    public void saveCaseAnalsy1(){

        //获取当前日期的前一天
//        String lastDay = CommonUtilHll.getLastDay(new Date());
        // int month = CommonUtilHll.getLastDayMonth(new Date());

        /**
         第一步获取 所有的stap_code,dept_code
         -- 物料在价格表有数据就说明他此物料
         -- 物料在盘点数据中出现说明部门有此物料

         select DISTINCT * from (
         select p.stap_code as stapCode,p.dept_code as deptCode from tql_stap_price p
         left join sys_dept t on t.dept_code =p.dept_code
         where t.pdept_code in (
         select concat(kingdeeDeptCode,'002' )from tql_hll_kingdee where flag=1
         )

         union
         select  p.stap_code as stapCode,p.dept_code as deptCode from tql_pandian_data p
         left join sys_dept t on t.dept_code =p.dept_code
         where t.pdept_code in (
         select concat(kingdeeDeptCode,'002' )from tql_hll_kingdee where flag=1
         )
         and
         MONTH(p.create_time) = MONTH(CURRENT_DATE()) or MONTH(p.create_time) = MONTH(CURRENT_DATE())-1
         AND YEAR(p.create_time) = YEAR(CURRENT_DATE())
         )t
         */
        List<CaseAnalsysDto> list=anotherDataBaseService.findStapCodeOfDeptCode();
        /**
         第二步
         -- 第二部去case_anlasys查询currentConsume,currentCase
         -- 这两个值
         select currentCase,currentConsume,stapCode,deptCode from tql_case_anlasys1
         where id in(
         select max(id) from tql_case_anlasys1
         where concat(deptCode,stapCode) in('')
         group by deptCode,stapCode
         )
         */
        if(CollectionUtils.isEmpty(list))return ;
        String[] deptCodeStapCodeArr = list.stream().map(dto -> dto.getDeptCode() + dto.getStapCode()).toArray(String[]::new);

        Date currentCalTime=getCalTime(-1);
        Date lastCalTime=getLastCalTime(currentCalTime);
        int month=CommonUtilHll.getCurrentMonth(lastCalTime);
        List<CaseAnalsysDto> list1=null;
        if(!Objects.isNull(lastCalTime))
            list1= anotherDataBaseService.findCurrentCaseAndCurrentConsume(deptCodeStapCodeArr,month);
        //-----给list里的lastConsume,lastCase赋值
        if(!CollectionUtils.isEmpty(list1))
        {
            for (CaseAnalsysDto dto1 : list1) {
                for (CaseAnalsysDto dto : list) {
                    if (dto1.getStapCode().equals(dto.getStapCode()) && dto1.getDeptCode().equals(dto.getDeptCode())) {
                        dto.setLastConsume(dto1.getCurrentConsume());
                        dto.setLastCase(dto1.getCurrentCase());
                        break;
                    }
                }
            }

        }
        //-----给list里的lastConsume,lastCase赋值
/*
        shopName
                shopCode
        stapName
                stapCode
        lastCase昨日库存初始值0
                currentCase=lastCase+采购1|2+当日调入-当日调出-当日消耗
        currentDate
                consumeDay日均消耗=lastConsume+currentConsume
        lastConsume=上一个currentConsume
        currentConsume=out表stap的累加值
        flowDate流转天数=currentCase/consumeDay
        */

/**currentConsume
 *  //currentConsume=out表stap的累加值
 *  out表的reportDate是否是当天的实时消费时间
 * select sumquota,deptCode,stap_code as stapCode
 * from
 * tql_stap_out_change12
 * where reportDate=
 */
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(currentCalTime);
        Long FDate = Long.parseLong(dateStr);
        String dateStr1 = sdf.format(lastCalTime);
        Long lastCalTime1 = Long.parseLong(dateStr1);
        List<CaseAnalsysDto>   list2= anotherDataBaseService.findCurrentConsume( FDate,month);

        //-----给list里的currentConsume赋值
        if(!CollectionUtils.isEmpty(list2))
        {
            for (CaseAnalsysDto dto1 : list2) {
                for (CaseAnalsysDto dto : list) {
                    if (dto1.getStapCode().equals(dto.getStapCode()) && dto1.getDeptCode().equals(dto.getDeptCode())) {
                        dto.setCurrentConsume(dto1.getCurrentConsume());
                        break;
                    }
                }
            }

        }


/**
 * 获取inNum,inids的数据
 * 给inNum,inids,inmonth赋值
 */
        List<CaseAnalsysDto>   list3= anotherDataBaseService.findCurrentInum( String.valueOf(FDate),month);

        if(!CollectionUtils.isEmpty(list3))
        {
            for (CaseAnalsysDto dto1 : list3) {
                for (CaseAnalsysDto dto : list) {
                    if (dto1.getStapCode().equals(dto.getStapCode()) && dto1.getDeptCode().equals(dto.getDeptCode())) {
                        dto.setInNum(dto1.getInNum());
                        dto.setInids(dto1.getInids());
                        dto.setInmonth(month);
                        break;
                    }
                }
            }

        }

        for(CaseAnalsysDto each:list)
        {
            BigDecimal currentCase1=CalculatedValueUtil.additionDecimal(each.getLastCase(),null==each.getInNum()?BigDecimal.ZERO:each.getInNum());
            BigDecimal currentCase=CalculatedValueUtil.subtractionBigDecimal(currentCase1,null==each.getCurrentConsume()?BigDecimal.ZERO:each.getCurrentConsume());
            //currentCase=lastCase+采购1|2+当日调入-当日调出-当日消耗
            each.setCurrentCase(currentCase);
            BigDecimal lastConsume=null==each.getLastConsume()?BigDecimal.ZERO:each.getLastConsume();
            BigDecimal currentConsume=null==each.getCurrentConsume()?BigDecimal.ZERO:each.getCurrentConsume();
            BigDecimal sumConsume=CalculatedValueUtil.additionDecimal(lastConsume,currentConsume);
            //日均消耗
            BigDecimal consumeDay=CalculatedValueUtil.division(sumConsume,new BigDecimal(2));
            each.setConsumeDay(consumeDay);
            //    flowDate流转天数=currentCase/consumeDay
            if(null!=consumeDay&&!BigDecimal.ZERO.equals(consumeDay))
            {
                BigDecimal flowDate=CalculatedValueUtil.division(each.getCurrentCase(),consumeDay);
                each.setFlowDate(flowDate.intValue());
            }
            each.setCurrentCalDate(FDate);
            each.setLastCalDate(lastCalTime1);

        }

//批量插入
        int month1=CommonUtilHll.getCurrentMonth(currentCalTime);
        anotherDataBaseService.batchInsert(list,month1);

    }

    private Date getCalTime(int flag) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, flag);
        Date date2 = cal.getTime();
        return  date2;
    }

    private Date getLastCalTime(Date calTime) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(calTime);

        if (cal.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR) &&
                cal.get(Calendar.MONTH) == Calendar.JANUARY &&
                cal.get(Calendar.DAY_OF_MONTH) == 1) {
            return null;
        } else {
            cal.add(Calendar.DATE, -1);
            return cal.getTime();
        }
    }


    @Override
    public void saveCaseAnalsy() {
        //获取当前日期的前一天
        String lastDay = CommonUtilHll.getLastDay(new Date());
        int month = CommonUtilHll.getCurrentMonth(new Date());
        //获取使用物料
        Map map = new HashMap();
        map.put("paramTime",lastDay);
        map.put("tableName",CommonUtil.TABLE_OUT_CHANGE+month);
        /*map.put("tableName","tql_stap_out_change"+month);*/
        List<TqlStapoutChangeEntity> kk = stapOutChangeService.getStapOutChangeList(map);
        if (!CollectionUtils.isEmpty(kk)){
            List<String> deptCodes = kk.stream().map(l-> stockCalculateMapper.selectDeptCode((long) l.getDeptId())).collect(Collectors.toList());
            List<String> stapCodes = kk.stream().map(TqlStapoutChangeEntity::getStapCode).collect(Collectors.toList());
            List<TqlStapProlossItemVO> listB = genCostAnalysService.selectInChangeData(month,deptCodes,stapCodes,lastDay);
            /*List<TqlStapProlossItemVO> listB = anotherDataBaseService.stapProlossItemVOList(month,deptCodes,stapCodes,sdf.format(date));*/
            kk.forEach(m->{
                TqlCaseAnlasysEntity bean = new TqlCaseAnlasysEntity();
                bean.setShopCode(String.valueOf(m.getShopId()));
                bean.setShopName(stockCalculateMapper.selectShopName(String.valueOf(m.getShopId())));
                bean.setStapCode(m.getStapCode());
                // 昨日库存
                LastCaseDTO dto = new LastCaseDTO();
                String deptCode =stockCalculateMapper.selectDeptCode((long) m.getDeptId());
                dto.setShopCode(String.valueOf(m.getShopId()));
                dto.setStapCode(m.getStapCode());
                dto.setDeptCode(deptCode);
                LastCaseVo lastCaseVo = stockCalculateMapper.selectLastCase(dto,CommonUtil.TABLE_CASE_ANLASYS+month);
                if (Objects.isNull(lastCaseVo)){
                    bean.setLastCase(new BigDecimal(0));    //昨日库存
                    bean.setLastConsume(new BigDecimal(0)); //昨日库存消耗
                }else {
                    if (lastCaseVo.getCurrentCase() == null){ //昨日库存
                        bean.setLastCase(new BigDecimal(0));
                    }else {
                        bean.setLastCase(lastCaseVo.getCurrentCase());
                    }
                    if (lastCaseVo.getCurrentConsume() == null){   //昨日库存消耗
                        bean.setLastConsume(new BigDecimal(0));
                    }else {
                        bean.setLastConsume(lastCaseVo.getCurrentConsume());
                    }
                }
                /*List<TqlStapProlossItemVO> listA = genCostAnalysService.selectInChange(month,deptCode,m.getStapCode(),dateTime,dateTime);*/
                if (listB.size() > 0){
                    //采购+调入
                    BigDecimal resultAddSum = listB.stream()
                            .filter(u->u.getDeptCode().equals(deptCode))
                            .filter(d->d.getStapCode().equals(m.getStapCode()))
                            .filter(g->g.getType().equals(1))
                            .filter(g->g.getType().equals(2))
                            .filter(g->g.getType().equals(3))
                            .map(TqlStapProlossItemVO::getStapAmout)
                            .reduce(BigDecimal.ZERO,BigDecimal::add);
                    //调出
                    BigDecimal resultSubStaSum = listB.stream()
                            .filter(u->u.getDeptCode().equals(deptCode))
                            .filter(d->d.getStapCode().equals(m.getStapCode()))
                            .filter(g->g.getType().equals(4))
                            .map(TqlStapProlossItemVO::getStapAmout)
                            .reduce(BigDecimal.ZERO,BigDecimal::add);
                    bean.setOutAmount(resultSubStaSum);

                    //采购数量
                    BigDecimal procureAmount = listB.stream()
                            .filter(u->u.getDeptCode().equals(deptCode))
                            .filter(d->d.getStapCode().equals(m.getStapCode()))
                            .filter(g->g.getType().equals(1))
                            .filter(g->g.getType().equals(2))
                            .map(TqlStapProlossItemVO::getStapAmout)
                            .reduce(BigDecimal.ZERO,BigDecimal::add);
                    bean.setProcureAmount(procureAmount);

                    //调入数量
                    BigDecimal callAmount = listB.stream()
                            .filter(u->u.getDeptCode().equals(deptCode))
                            .filter(d->d.getStapCode().equals(m.getStapCode()))
                            .filter(g->g.getType().equals(3))
                            .map(TqlStapProlossItemVO::getStapAmout)
                            .reduce(BigDecimal.ZERO,BigDecimal::add);
                    bean.setCallAmount(callAmount);

                    //bean.setCurrentConsume(m.getSumquota()); //当前消耗
                    bean.setCurrentConsume((m.getSumquota() == null || m.getSumquota().compareTo(BigDecimal.ZERO) == 0)?BigDecimal.ZERO:m.getSumquota());
                    BigDecimal currentCase = CalculatedValueUtil.additionDecimal(bean.getLastCase(),resultAddSum);
                    BigDecimal ff = CalculatedValueUtil.subtractionBigDecimal(currentCase,resultSubStaSum);
                    bean.setCurrentCase(CalculatedValueUtil.subtractionBigDecimal(ff,m.getSumquota()));
                    /*BigDecimal currentCase = CommonUtilHll.addDecimal(bean.getLastCase(),resultAddSum);
                    BigDecimal ff = CommonUtilHll.subtractDecimal(currentCase,resultSubStaSum);
                    bean.setCurrentCase(CommonUtilHll.subtractDecimal(ff,m.getSumquota()));*/
                    //bean.setCurrentCase(bean.getLastCase().add(resultAddSum).subtract(resultSubStaSum).subtract(m.getSumquota())); //当前库存
                   /* BigDecimal consumeDay = CommonUtilHll.addDecimal(bean.getCurrentConsume(),bean.getLastConsume());
                    BigDecimal divideConsumeDay = CommonUtilHll.divideDecimal(consumeDay,new BigDecimal(2));*/
                    BigDecimal consumeDay = CalculatedValueUtil.additionDecimal(bean.getCurrentConsume(),bean.getLastConsume());
                    BigDecimal divideConsumeDay = CalculatedValueUtil.division(consumeDay,new BigDecimal(2));
                    bean.setConsumeDay(divideConsumeDay);
                }
                bean.setCurrentDate(lastDay);
                bean.setDeptCode(deptCode);
                bean.setCreateTime(new Date());
                anotherDataBaseService.saveCaseAnlasys(bean, CommonUtil.TABLE_CASE_ANLASYS + month);
            });
        }
    }
}
